package com.bluetooth.heartchecked.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bluetooth.heartchecked.App;
import com.bluetooth.heartchecked.bean.HeartRateEntity;

import java.util.ArrayList;
import java.util.List;

public class DBManager {

    private DBHelper helper;
    private SQLiteDatabase db;

    private static DBManager instance;

    private DBManager() {
        helper = new DBHelper(App.getInstance());
        db = helper.getWritableDatabase();
    }

    public synchronized static DBManager getInstance() {
        if (instance == null) {
            instance = new DBManager();
        }
        return instance;
    }

    public void add(HeartRateEntity entity) {
        db.beginTransaction();
        try {
            String sql = "INSERT INTO heart VALUES(null, ?, ?)";
            db.execSQL(sql, new Object[]{entity.getTime(), entity.getRate()});
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

    public List<HeartRateEntity> find(int minRate, int maxRate) {
        List<HeartRateEntity> entities = new ArrayList<>();
        Cursor c = db.rawQuery("SELECT * FROM heart", null);
        while (c.moveToNext()) {
            HeartRateEntity entity = new HeartRateEntity();
            String time = c.getString(c.getColumnIndex("time"));
            int rate = c.getInt(c.getColumnIndex("rate"));
            if (rate >= minRate && rate <= maxRate) {
                entity.setTime(time);
                entity.setRate(rate);
                entities.add(entity);
            }
        }
        c.close();
        return entities;
    }

    public List<HeartRateEntity> findAll() {
        List<HeartRateEntity> entities = new ArrayList<>();
        Cursor c = db.rawQuery("SELECT * FROM heart", null);
        while (c.moveToNext()) {
            HeartRateEntity entity = new HeartRateEntity();
            String time = c.getString(c.getColumnIndex("time"));
            int rate = c.getInt(c.getColumnIndex("rate"));
            entity.setTime(time);
            entity.setRate(rate);
            entities.add(entity);
        }
        c.close();
        return entities;
    }

    public void clearAll() {
        db.execSQL("delete from heart");
    }

    public void closeDB() {
        db.close();
    }

}
